import json

from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection

from apps.goods.models import SKU
from meiduo_mall.utils.cookiesecret import CookieSecret


class CartsSelectAllView(View):
    def put(self, request):
        # 接收参数
        selected = json.loads(request.body.decode()).get('selected', True)

        # # 校验参数
        if not isinstance(selected, bool):
            return JsonResponse({'code': 400, 'errmsg': 'selected类型不对'})

        # # 判断是否登录
        user = request.user
        if user.is_authenticated:
            # redis
            # 1.取出购物车的所有数据
            carts_redis_client = get_redis_connection('carts')
            carts_data = carts_redis_client.hgetall(user.id)

            # 2.遍历购物车的数据
            for k, v in carts_data.items():
                sku_id = int(k.decode())
                carts_dict = json.loads(v.decode())

                carts_dict['selected'] = selected

                # 3.根据前端的参数 修改  seleted 值
                carts_redis_client.hset(user.id, sku_id, json.dumps(carts_dict))
            return JsonResponse({'code': 0, 'errmsg': 'OK'})

        else:
            # cookie
            # 1.取出购物车的所有数据
            cookie_str = request.COOKIES.get('carts')

            response = JsonResponse({'code': 0, 'errmsg': 'OK'})

            if cookie_str is not None:
                carts_dict = CookieSecret.loads(cookie_str)

                # 2.遍历购物车的数据
                for sku_id in carts_dict:

                    carts_dict[sku_id]['selected'] = selected

                dumps_cookie_str = CookieSecret.dumps(carts_dict)

                # 3.根据前端的参数 修改  seleted 值
                response.set_cookie('carts', dumps_cookie_str, max_age=14 * 3600 *24)

            # # 返回响应 json
            return response


class CartsView(View):

    def delete(self, request):

        # 1.接收参数
        sku_id = json.loads(request.body.decode()).get('sku_id')

        # 2.校验参数
        try:
            sku = SKU.objects.get(pk=sku_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '商品不存在'})

        # 3.手动判断是否
        user = request.user
        dumps_cookie_str = ''
        if user.is_authenticated:
            # redis -hdel
            carts_redis_client = get_redis_connection('carts')

            carts_redis_client.hdel(user.id, sku.id)
        else:
            # cookie --del
            # 1.从cookie 取出 加密 的 购物车数据
            cookie_str = request.COOKIES.get('carts')
            # 2.如果有值 --解密
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}

            # 3.判断 sku_id 在不在购物车
            if sku_id in cart_dict:
                # 4. 如果在 字典里面删除 key ; del k ; 如果k 报错
                del cart_dict[sku_id]
                dumps_cookie_str = CookieSecret.dumps(cart_dict)

        # 统一返回响应对象
        response = JsonResponse({'code': 0, 'errmsg': 'OK'})
        if not user.is_authenticated:
            response.set_cookie('carts', dumps_cookie_str, max_age=3600 * 14 * 24)
        return response

    def put(self, request):

        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 2.校验参数
        try:
            sku = SKU.objects.get(pk=sku_id)
        except Exception as e:
            return JsonResponse({'code': '400', 'errmsg': 'OK'})

        # 3.手动判断是否
        user = request.user
        dumps_cookie_str = ""
        if user.is_authenticated:
            # redis --hset
            # 1. 获取redis 连接对象
            carts_redis_client = get_redis_connection('carts')
            # 2.构建 更新的数据
            new_dict = {'count': count, 'selected': selected}
            # 3.直接覆盖 hset(k,属性, v)
            carts_redis_client.hset(user.id, sku_id, json.dumps(new_dict))
        else:
            # cookie --
            # 1.从cookie 取出 加密 的 购物车数据
            cookie_str = request.COOKIES.get('carts')
            # 2.如果有值 --解密
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}

            # 3.直接覆盖 购物车数据
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 4.加密修改完毕的数据
            dumps_cookie_str = CookieSecret.dumps(cart_dict)

        # 数据格式 dict --> sku --carts
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,

            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        # 返回响应
        response = JsonResponse({'code': '0', 'errmsg': 'OK', 'cart_sku': cart_sku})
        # 二次判断是否登录 -- 没登录 -- set_cookie(k,v,seconds)
        if not user.is_authenticated:
            response.set_cookie('carts', dumps_cookie_str, max_age=14 * 3600 * 24)
        return response

    def get(self, request):
        user = request.user
        if user.is_authenticated:
            # redis 登录
            carts_redis_client = get_redis_connection('carts')

            # hgetall-->dict {b'2',b'{count:2:selected:True}'}
            carts_data = carts_redis_client.hgetall(user.id)

            # dict.keys() dict.values() dict.items()
            # carts_dict = {}
            # for k, v in carts_data.items():
            #     sku_id = int(k.decode())
            #     sku_dict = json.loads(v.decode())
            #     # 构建一个 新字典
            #     carts_dict[sku_id] = sku_dict

            # 字典推导式
            carts_dict = {int(k.decode()): json.loads(v.decode()) for k, v in carts_data.items()}

        else:
            # cookie 未登录
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}

        # count selected sku_id ---> SKU查询sku
        sku_ids = carts_dict.keys()

        # 将 数据 --json
        sku_list = []

        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,

                'count': carts_dict.get(sku_id).get('count'),
                'selected': carts_dict.get(sku_id).get('selected'),
            })

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'cart_skus': sku_list})

    def post(self, request):
        # 1.接收参数 json
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 2.校验参数 count 是否是int类型 selected bool
        if not all([sku_id, count]):
            return JsonResponse({'code': 400, 'errmsg': '参数不齐!'})
        try:
            sku = SKU.objects.get(pk=sku_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '商品不存在!'})

        try:
            count = int(count)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': 'count类型问题!'})

        if not isinstance(selected, bool):
            return JsonResponse({'code': 400, 'errmsg': 'selected类型问题!'})

        # 3.手动判断是否登录 user.is_authenticated
        user = request.user
        if user.is_authenticated:
            # 3.1 登录 --redis
            print('3.1 登录 --redis')
            # 1. 链接 redis 对象
            carts_redis_client = get_redis_connection('carts')

            # 2. 获取当前用户 的所有购物车数据 -- bytes    {b'1':b'{count:2,selected:true}'}
            client_data = carts_redis_client.hgetall(user.id)

            # 3. 判断 当前商品以前有没有添加过-- hset()
            # str(sku_id).encode() 将 int类型sku_id-->str()-->字符串-->encode()--->b'sku_id'
            if str(sku_id).encode() in client_data:

                # 3.1 根据 sku_id 取对应商品的购物车数据 b'{count:2,selected:true}' == client_data[str(sku_id).encode() ]
                child_dict = json.loads((client_data[str(sku_id).encode()]).decode())

                # 3.2 取出老的 购买个数 + 新的购买个数
                count = child_dict['count'] + count

                # 3.3 更新数据--------------k  -----v ------ value
                carts_redis_client.hset(user.id, sku_id, json.dumps({'count': count, 'selected': selected}))

            else:
                #   直接新增 hset()
                carts_redis_client.hset(user.id, sku_id, json.dumps({'count': count, 'selected': selected}))

            # 4.返回响应对象
            return JsonResponse({'code': 0, 'errmsg': 'Ok!'})

        else:
            # 3.2 未登录 --cookie
            print('未登录 --cookie')
            # 1. 取出Cookie的购物车数据  request.COOKIES.get('carts')
            cart_str = request.COOKIES.get('carts')

            # 2. 解密--cart_dict = {有值}
            # 3.创建一个空字典 cart_dict = { }
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            # 4.如果这个商品 存在 以前的 cookie数据中
            if sku_id in cart_dict:
                #    取出老的商品 个数 + count 新的个数  累加
                origin_count = cart_dict[sku_id]['count']
                count = origin_count + count

            # 5.无论是新sku 还是 老sku --直接都覆盖
            cart_dict[sku_id] = {

                'count': count,
                'selected': selected
            }
            #
            # 6.加密--str
            cookie_cart_str = CookieSecret.dumps(cart_dict)
            # 7.设置cookie
            response = JsonResponse({'code': 0, 'errmsg': 'Ok!'})
            response.set_cookie('carts', cookie_cart_str, max_age=14 * 24 * 3600)
            # 8.返回 json
            return response
